import os
import argparse
import time
from pylxd import Client
import subprocess
from ip import *
import re


IP_PREFIX = "10.112.43"
IP_TARGET = "{ipplaceholder}"
GATEWAY_TARGET = "{gatewayplaceholder}"
REPLACE_FILE = "./template/50-cloud-init.yaml"
TEMPLATE_FILE = "./template/50-cloud-init.yaml.template"


parser = argparse.ArgumentParser()
parser.add_argument("username", help = "username")
parser.add_argument("passwd", help = "password")

args = parser.parse_args()


def execute(container_name, commands):
    lxc_commands = ['lxc', 'exec', container_name, '--', *commands]
    return subprocess.run(lxc_commands, capture_output=True)


def replace(file, str1, str2, target1, target2):
    with open(file, "+w") as fw:
        with open(TEMPLATE_FILE,'r') as fr:
            t = fr.read()
            t = t.replace(target1, str1)
            t = t.replace(target2, str2)
            fw.write(t)


def prepare():
    """
    place ip and gateway into netplan config file
    """
    print("search free ip ...")
    ip = get_free_ip(IP_PREFIX)
    print(f"try to alocate ip: {ip}")
    gateway = IP_PREFIX + ".1"
    replace(REPLACE_FILE, ip, gateway, IP_TARGET, GATEWAY_TARGET)

if __name__== "__main__":
    prepare()

    container = args.username
    passwd = args.passwd

    usermod = f"usermod -l {container} -d /home/{container} -m ubuntu"
    chpasswd = f"echo {container}:{passwd} | chpasswd"
    netplan_apply = "netplan apply"
    reboot = "reboot"
    command = [
        f"lxc launch ubuntu:focal {container}", # create container
        f"lxc file push ./template/50-cloud-init.yaml {container}/etc/netplan/",
        f"lxc file push ./template/sshd_config {container}/etc/ssh/",
        f"echo \'{netplan_apply}\' > cp.tmp.bash",
        f"echo \'{usermod}\' >> cp.tmp.bash",
        f"echo \'{chpasswd}\' >> cp.tmp.bash",
        f"lxc file push ./cp.tmp.bash {container}/",
        f"rm cp.tmp.bash",
    ]

    command_in_container = [
        # ['usermod', '-l', f"{container}", "-d", f"/home/{container}", '-m', 'ubuntu'],
        # [f"echo", f"{chpasswd}", ">", 'cp.tmp.bash'],
        ['reboot'],
        ['bash', '/cp.tmp.bash'],
        ['rm', '/cp.tmp.bash'],
    ]

    for idx, c in enumerate(command):
        print(f"exec: {c}")
        os.system(c)
        if idx == 0:
            time.sleep(10)  # wait container start and finish initialization
            # con = client.containers.get(container)
            # start = time.time()
            # while con.status != "Running": # wait container start
            #     elapse = time.time() - start
            #     if elapse > 10: # max wait time
            #         exit()

    ## pylxd BUG. NO FIXED YET
    # print(client.containers.all())
    # con = client.containers.get(container)
    # con.execute(command_in_container)
    # con.restart()

    for cic in command_in_container:
        print(execute(container, cic))

